using UnityEngine;
using System.Collections;

public class Car : MonoBehaviour {
	
	private Vector3 initSize;
	private bool killable;
	private bool inResize;
	
	public GameObject fire;
	public GameObject wheel;
	public float launchSpeed;
	
	// Use this for initialization
	void Start () {
		Controller.spawnedCar = gameObject;
		killable = true;
		initSize = transform.localScale;
	}
	
	// Update is called once per frame
	void Update () {
		if(Controller.inGame)
			rigidbody.velocity = new Vector3(Input.GetAxis("Horizontal") * Controller.carVelocity, Input.GetAxis("Vertical") * Controller.carVelocity, 0);
	}
	
	public void Resize()
	{	
		if(!inResize)
		{
			inResize = true;
			killable = false;
			StartCoroutine(ResizeHelper());
		}
	}
	
	private IEnumerator ResizeHelper ()
	{
		float i = 0;
		
		while(i < Controller.growthTime)
		{
			transform.localScale = initSize + (Vector3.one * Controller.maxGrowthFactor) * Mathf.Sin((i/Controller.growthTime) * Mathf.PI);
			transform.localRotation = Quaternion.Euler(Vector3.right * 360 * Mathf.Sin((i/Controller.growthTime) * Mathf.PI));
			i += Time.deltaTime;
			yield return null;
		}
		
		transform.localScale = initSize;
		killable = true;
		inResize = false;
		
		Controller.LevelUp();
	}
	
	public void Die()
	{
		GameObject crosshair = GameObject.Find("Crosshair(Clone)");
		if(crosshair != null)
			Destroy(crosshair);
		
		GameObject explosion = GameObject.Instantiate(fire, transform.position, Quaternion.identity) as GameObject;
		explosion.rigidbody.velocity = Vector3.up * launchSpeed;
		for (int i = 0; i < 5; ++i)
		{
			explosion = GameObject.Instantiate(fire, transform.position + new Vector3(Random.Range(-1f, 2f), Random.Range(-1f, 2f), 0), Quaternion.identity) as GameObject;
			explosion.rigidbody.velocity = Vector3.up * launchSpeed;
		}
		StartCoroutine(SpawnSnake());
		Controller.Load();
		Destroy(gameObject);
	}
	
	public void FireDie ()
	{
		if(killable)
			Die();
	}
	
	private IEnumerator SpawnSnake ()
	{
		GameObject snakeWheel = GameObject.Instantiate(wheel) as GameObject;
		snakeWheel.transform.position = transform.position;
		snakeWheel.transform.localScale = Vector3.zero;
		
		while (snakeWheel.transform.localScale.x < 1)
		{
			snakeWheel.transform.localScale = Vector3.Lerp(snakeWheel.transform.localScale, Vector3.one, 300 * Time.deltaTime);
			yield return null;
		}
	}
}
